<template>
  <!-- 滁州监察端劳资专管员 -->
  <div ref="mainCon" class="container">
    <topTitle :titleText="titleText"></topTitle>
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField">
          <el-col :lg="8" :xl="6">
            <el-form-item label="人员姓名" class="row-padding-bottom">
              <el-input
                placeholder="请输入姓名或身份证号"
                clearable
                v-model="filterField.keyword"
                @blur="filterField.keyword = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-form-item>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchTable"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
            <!-- <el-button class="commonBut saveBtn funComBut" icon="icon iconfont icondaochu" v-sdc @click="exportList">
                            <span class="opetareText">导出</span>
                        </el-button> -->
            <exportBtn
              :dataLen="tableData.length"
              :filterField="filterField"
              :responseType="`get`"
              api="api-e/cs/qualification/expand/exportbyconditions"
            ></exportBtn>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <!-- 列表 -->
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableData"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          v-loading="loading"
          style="border: 1px solid #dfe6ec"
          @sort-change="sortChange"
        >
          <el-table-column align="center" prop="imgPath" label="身份证照片">
            <template slot-scope="scope">
              <el-image
                v-if="scope.row.imgPath"
                style="width: 50px; height: 50px; top: 3.5px"
                :src="scope.row.imgPath"
                :preview-src-list="scope.row.idcardImgList"
              >
              </el-image>
              <el-image
                v-else
                src="../../../static/img/employee/card.png"
                alt=""
                style="width: 50px; height: 50px; top: 3.5px"
              />
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="name"
            label="姓名"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="idCard"
            label="身份证号"
            min-width="120"
          >
            <template slot-scope="scope">
              <p>{{ scope.row.idcard | deseHandler(4, 4, '*') || '--' }}</p>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="sexValue"
            label="性别"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="nationalityValue"
            label="民族"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="createTime"
            label="录入时间"
            sortable="custom"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column align="left" label="操作" fixed="right" width="180">
            <template slot-scope="scope">
              <el-link type="primary" @click="toDetail(scope.row)"
                >查看</el-link
              >
              <el-link type="primary" @click="toUpdate(scope.row)"
                >修改</el-link
              >
              <el-link type="primary" @click="toDelete(scope.row)"
                >删除</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <!-- filterField为搜索条件 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :requestUrl="requestUrl"
          :filterField="filterField"
        ></Pagination>
      </div>
    </div>
    <el-dialog
      title="修改劳资资质信息"
      :visible.sync="formVisible"
      :close-on-click-modal="false"
      @close="cancel('formData')"
      custom-class="brand-dialog-min-width"
      :modal-append-to-body="false"
      :append-to-body="true"
      width="640px"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="120px"
        class="demo-formData mrT8"
      >
        <el-row>
          <el-form-item label="姓名：" class="row-padding-bottom">
            <el-input
              class="dialogSingleInp"
              v-model="formData.name"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="身份证号：" class="row-padding-bottom">
            <el-input
              class="dialogSingleInp"
              v-model="formData.idcard"
              autocomplete="off"
              disabled
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="证书编号："
            class="row-padding-bottom"
            prop="certificateNumber"
          >
            <el-input
              class="dialogSingleInp"
              v-model="formData.certificateNumber"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="发证日期：" prop="effectiveStartDate">
            <el-date-picker
              class="dialogSingleInp"
              type="date"
              placeholder="请选择发证日期"
              v-model="formData.effectiveStartDate"
              :picker-options="pickerOptions"
              @change="effectiveStartDateChange"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="到期日期：" prop="effectiveEndDate">
            <el-date-picker
              class="dialogSingleInp"
              type="date"
              placeholder="到期日期"
              v-model="formData.effectiveEndDate"
              disabled
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              prop="upLoadFile"
              label="证书附件："
              class="upLoadDomContainer"
              v-model="formData.fileList"
            >
              <uploadAnnex
                @getFileList="getFileList"
                :limitationFactor="limitationFactor"
                @getFile="getFileInsurance"
                :upLoadFile="upLoadFile"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-model="formData.fileList">
            <uploadResult
              style="margin-left: 116px !important"
              :resultList="upLoadFile"
              @callBackResult="getFile"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              prop="empAppoint"
              label="劳资专管员企业任命文件："
              class="agreementBox"
              v-model="formData.empAppoint"
            >
              <uploadAnnex
                @getFileList="getEmpAppointList"
                :limitationFactor="limitationFactorTwo"
                @getFile="getEmpAppoint"
                :upLoadFile="empAppointList"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" v-model="formData.empAppoint">
            <uploadResult
              style="margin-left: 116px !important"
              :resultList="empAppointList"
              @callBackResult="getEmpAppoint"
            />
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="cancel" class="cancel">取消</el-button>
        <el-button
          type="primary"
          @click.native="saveForm"
          v-sdc
          class="save"
          :loading="isSaveLoading"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import common from '../../kits/common'
import scrollTable from '@/mixin/scrollTable.js'

export default {
  name: 'laborListCz',
  mixins: [scrollTable],
  data() {
    var checkUpLoadFile = (rule, value, callback) => {
      if (this.upLoadFile.length == 0) {
        return callback(new Error('请上传证书附件'))
      } else {
        callback()
      }
    }
    var checkEmpAppoint = (rule, value, callback) => {
      if (this.empAppointList.length == 0) {
        return callback(new Error('请上传劳资专管员企业任命文件'))
      } else {
        callback()
      }
    }
    return {
      titleText: '劳资专管员',
      requestUrl: 'api-e/cs/qualification/expand/listbyconditions', //表格请求路径
      tableData: [],
      idcardImgList: [],
      back: true,
      filterField: {
        keyword: '',
      },
      loading: true,
      isShow: false,
      formVisible: false,
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传附件的个数设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeOne', //自定义上传格式校验类型
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        messagetip:
          '请上传证书附件（必须包含证书编号内容、发证日期等信息），附件格式支持png，jpg，jpeg，最多上传10个附件', //自定义报错提示语
        methodTip:
          '请上传证书附件（必须包含证书编号内容、发证日期等信息），附件格式支持png，jpg，jpeg，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
      upLoadFile: [],
      srcList: [],
      oldSrcList: [],
      //发证日期当天三年内
      pickerOptions: {
        disabledDate: (time) => {
          return (
            time.getTime() > Date.now() ||
            time.getTime() == Date.now() ||
            time.getTime() <
              new Date().setFullYear(new Date().getFullYear() - 3)
          )
        },
      },
      formData: {
        name: '',
        idcard: '',
        certificateNumber: '',
        effectiveStartDate: '',
        effectiveEndDate: '',
        employeeId: '',
        files: [],
        empAppoint: [],
      },
      formRules: {
        certificateNumber: [
          {
            required: true,
            pattern: /^[a-zA-Z0-9]{1,20}$/,
            message: '证书编号格式不正确',
            trigger: ['blur', 'change'],
          },
        ],
        effectiveStartDate: [
          {
            required: true,
            message: '请选择发证日期',
            trigger: 'change',
          },
        ],
        effectiveEndDate: [
          {
            required: true,
            message: '请先选择发证日期',
            trigger: 'change',
          },
        ],
        upLoadFile: [
          {
            required: true,
            validator: checkUpLoadFile,
            trigger: 'blur',
          },
        ],
        empAppoint: [
          {
            required: true,
            validator: checkEmpAppoint,
            trigger: 'blur',
          },
        ],
      },
      isSaveLoading: false,
      id: '',
      empAppointList: [],
      limitationFactorTwo: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传附件的个数设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        fileId: 'managerUpLoadFile', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'managerUpLoadFileForm', //自定义id解决一个页面包含多个上传附件
        messagetip:
          '请上传劳资员任命证书，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件', //自定义报错提示语
        methodTip:
          '请上传劳资员任命证书，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
    }
  },
  watch: {
    upLoadFile(val) {
      if (val.length > 0) {
        this.$refs.formData.clearValidate('upLoadFile')
      }
    },
    empAppointList(val) {
      if (val.length > 0) {
        this.$refs.formData.clearValidate('empAppoint')
      }
    },
  },
  created() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  methods: {
    getTableList(data) {
      this.tableData = data
      this.loading = false
      if (this.tableData.length < 1) {
        this.isShow = true
      } else {
        this.idcardImgList = []
        for (var i = 0; i < this.tableData.length; i++) {
          this.idcardImgList.push(this.tableData[i].imgPath)
        }
        for (var i = 0; i < this.tableData.length; i++) {
          var container = this.idcardImgList
          var frontArr = container.slice(0, i)
          var behindArr = container.slice(i, this.tableData.length)
          var list = behindArr.concat(frontArr)
          this.tableData[i].idcardImgList = list
        }
      }
    },
    //列表查询
    searchTable() {
      this.$refs.pagination.getTableListData()
    },
    // 导出
    // exportList() {
    //     if (this.tableData.length > 0) {
    //         window.location.href =
    //             common.commonApi +
    //             "api-e/cs/qualification/expand/exportbyconditions?keyword=" +
    //             this.filterField.keyword +
    //             "&orderBy=" +
    //             this.filterField.orderBy +
    //             "&access_token=" +
    //             localStorage.getItem("access_token");
    //     } else {
    //         this.$message({
    //             type: "error",
    //             message: "无数据导出"
    //         });
    //     }
    // },
    //查看详情
    toDetail(row) {
      this.$router.push({
        path: '/home/employee/employeeInfoC',
        name: 'employeeInfoC',
        query: {
          employeeId: row.employeeId,
          id: row.id,
          type: 'laborListCz',
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/employee/laborListCz',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    toUpdate(row) {
      this.formVisible = true
      this.isSaveLoading = true
      this.id = row.id
      this.getDetai(row.id, row.employeeId)
    },
    getDetai(id, employeeId) {
      this.axios({
        method: 'post',
        url: 'api-e/cs/qualification/expand/detail',
        data: {
          employeeId: employeeId,
          id: id,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.isSaveLoading = false
            var data = response.data.result
            this.formData.name = data.name
            this.formData.idcard = data.idcard
            this.formData.certificateNumber = data.certificateNumber
            this.formData.effectiveStartDate = data.effectiveStartDate
            this.formData.effectiveEndDate = data.effectiveEndDate
            this.upLoadFile = data.attachmentFiles
            this.empAppointList = data.empAppointFiles
            for (var i = 0; i < this.upLoadFile.length; i++) {
              this.srcList.push(this.upLoadFile[i].url)
              this.oldSrcList.push(this.upLoadFile[i].url)
            }
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
          console.log(error)
        })
    },
    toDelete(row) {
      this.$confirm('点击确定后将删除该人员的劳资信息，且无法恢复?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.delLaborInfo(row.id)
        })
        .catch(() => {})
    },
    delLaborInfo(id) {
      this.axios({
        method: 'post',
        url: 'api-e/cs/qualification/expand/delete',
        data: {
          id: id,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message({
              message: '删除成功',
              type: 'success',
            })
            this.$refs.pagination.getTableListData()
          } else {
            this.$message({
              message: response.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {})
    },
    effectiveStartDateChange() {
      let effectiveStartDate = this.formData.effectiveStartDate
      if (effectiveStartDate) {
        let year = +effectiveStartDate.substring(0, 4) + 3
        let expYear = effectiveStartDate.substring(4, 10)
        this.$nextTick(() => {
          this.formData.effectiveEndDate = year + expYear
          this.$refs.formData.clearValidate('effectiveEndDate')
        })
      } else {
        this.formData.effectiveEndDate = ''
      }
    },
    getFileList(val) {
      this.oldSrcList.push(val)
      this.srcList.push(val)
    },
    getFile(val) {
      this.upLoadFile = val
    },
    cancel(formData) {
      this.$refs['formData'].resetFields()
      this.formVisible = false
    },
    saveForm() {
      this.$refs.formData.validate((valid) => {
        this.formData.files = JSON.stringify(this.upLoadFile) //this.upLoadFile;
        this.formData.empAppointJson = JSON.stringify(this.empAppointList)
        if (valid) {
          this.isSaveLoading = true
          this.saveFormInfo()
        } else {
          return false
        }
      })
    },
    saveFormInfo() {
      this.axios({
        method: 'post',
        url: 'api-e/cs/qualification/expand/edit',
        data: {
          id: this.id,
          certificateNumber: this.formData.certificateNumber,
          effectiveStartDate: this.formData.effectiveStartDate,
          effectiveEndDate: this.formData.effectiveEndDate,
          files: this.formData.files,
          empAppointJson: this.formData.empAppointJson,
        },
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$message({
              type: 'success',
              message: '保存成功',
            })
            this.formVisible = false
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.isSaveLoading = false
        })
    },
    getEmpAppoint(val) {
      this.empAppointList = val
    },
  },
}
</script>

<style scoped lang="less">
@import '../../../static/css/filterArea.less';
.agreementBox {
  /deep/label {
    line-height: 20px;
  }
}
</style>
